#!/bin/bash

arr=(`echo $1 | tr '/' ' '`)

ORG=${arr[0]}
REPO=${arr[1]}
TAG=$2
SSH_USER=$3
SSH_IP=$4

echo "组织：${ORG}"
echo "仓库：${REPO}"
echo "标签：${TAG}"
echo "SSH用户：${SSH_USER}"
echo "SSH IP：${SSH_IP}"

FILE="${ORG}_${REPO}_${TAG}.tar"
GZ_FILE="${FILE}.gz"
IMAGE="${ORG}/${REPO}:${TAG}"

set -e

if [ -f ${GZ_FILE} ];
then
  echo "[$(date "+%Y-%m-%d %H:%M:%S")] ${GZ_FILE} 镜像文件已存在，无需创建临时镜像文件"
else
  # pull镜像
  docker pull ${IMAGE}
  echo "[$(date "+%Y-%m-%d %H:%M:%S")] ${GZ_FILE} 镜像文件不存在，开始创建临时镜像文件"
  docker save -o ${FILE} ${IMAGE}
  echo "[$(date "+%Y-%m-%d %H:%M:%S")] ${GZ_FILE} 压缩文件"
  tar cvzf ${GZ_FILE} ${FILE}
  rm -f ${FILE}
  echo "[$(date "+%Y-%m-%d %H:%M:%S")] ${GZ_FILE} 临时镜像文件创建完成"
fi

echo "[$(date "+%Y-%m-%d %H:%M:%S")] 开始上传临时镜像文件"
scp -i id_rsa -F ssh_config ${GZ_FILE} ${SSH_USER}@${SSH_IP}:~
echo "[$(date "+%Y-%m-%d %H:%M:%S")] 临时镜像文件上传完成"

ssh -i id_rsa -F ssh_config ${SSH_USER}@${SSH_IP} "echo \"[$(date "+%Y-%m-%d %H:%M:%S")] ${GZ_FILE} 解压文件\" && tar xzvf ${GZ_FILE} && docker load < ${FILE} && rm -f ${FILE} ${GZ_FILE} && echo \"[$(date "+%Y-%m-%d %H:%M:%S")] ${FILE} ${GZ_FILE} 删除临时镜像文件\""

# 删除镜像
# docker rmi docker pull ${IMAGE_NAME}:${IMAGE_TAG}
